import 'dart:collection';
import 'dart:core';
import 'dart:developer' as dev;
import 'dart:ui';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:changxindianzishangwu/cache/local_cache.dart';
import 'package:changxindianzishangwu/dao/common_language_dao.dart';
import 'package:changxindianzishangwu/dao/login_init_dao.dart';
import 'package:changxindianzishangwu/dao/select_user_dao.dart';
import 'package:changxindianzishangwu/model/base_model.dart';
import 'package:changxindianzishangwu/model/common_language_model.dart';
import 'package:changxindianzishangwu/model/select_user.dart';
import 'package:changxindianzishangwu/pages/contacts/new_firends_page.dart';
import 'package:changxindianzishangwu/pages/contacts/search_user_page.dart';
import 'package:changxindianzishangwu/pages/contacts/user_cart/user_check_page.dart';
import 'package:changxindianzishangwu/provider/conversion.dart';
import 'package:changxindianzishangwu/provider/currentMessageList.dart';
import 'package:changxindianzishangwu/util/colors.dart';
import 'package:changxindianzishangwu/util/head_url.dart';
import 'package:changxindianzishangwu/util/toast.dart';
import 'package:changxindianzishangwu/widget/login_zxing_dialog.dart';
import 'package:common_utils/common_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:get/get.dart';
import 'package:provider/provider.dart';
//import 'package:qrscan/qrscan.dart' as scanner;
import 'package:tencent_im_sdk_plugin/enum/V2TimConversationListener.dart';
import 'package:tencent_im_sdk_plugin/enum/message_elem_type.dart';
import 'package:tencent_im_sdk_plugin/manager/v2_tim_manager.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_callback.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_conversation.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_conversation_result.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_friend_info_result.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_message.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_value_callback.dart';
import 'package:tencent_im_sdk_plugin/tencent_im_sdk_plugin.dart';

import 'QR_view_example.dart';
import 'chat/message_c2c_page.dart';

class MessagePage extends StatefulWidget {
  MessagePage({Key key}) : super(key: key);

  @override
  _MessagePageState createState() => _MessagePageState();
}

class _MessagePageState extends State<MessagePage> {
  _MessagePageState() {
    getMessage();
  }

  String packageName = "MessagePage:";
  var height = 200;
  bool flag = false;
  List<Widget> conversationList = [];

  /// 刷新指示器Key
  GlobalKey<RefreshIndicatorState> _refreshIndicatorKey = GlobalKey();

  /// 会话结果对象
  List<V2TimConversation> _data = [];
  V2TimValueCallback<V2TimConversationResult> data;

  @override
  void initState() {
    super.initState();
    //TencentImPlugin.addListener(_imListener);
    _listingIm();
    SchedulerBinding.instance.addPostFrameCallback((_) {
      _refreshIndicatorKey.currentState.show();
    });
    getSelfId();
  }

  List<CommonLanguageBean> _leaveLists = [];
  List<CommonLanguageBean> _lists = [];

  //todo 此处需要从缓存获取
  getLeaveData() async {
    print('userId:${getUserInfo().userId}');
    _lists.clear();
    LinkedHashMap hashMap = await CommonLanguageDao.getData(2);
    if (!hashMap.containsKey("data")) {
      return;
    }
    CommonLanguageModel commonLanguageModel =
        CommonLanguageModel.fromJson(hashMap);

    if (mounted) _leaveLists.addAll(commonLanguageModel.data);
  }

  V2TimValueCallback<String> userId;

  getSelfId() async {
    userId = await TencentImSDKPlugin.v2TIMManager.getLoginUser();
  }

//离线回复
  sendLeaveData(sender) async {
    if (getUserSayHello() == 2 || getUserSayHello() == 3) {
      //
      if (sender != userId.data) {
        print("sender:" + sender);
        print("userId:" + userId.data);
        if (getAutoReply() != "") {
          if (sender != userId) {
            V2TimValueCallback<V2TimMessage> res = await TencentImSDKPlugin
                .v2TIMManager.v2TIMMessageManager
                .sendCustomMessage(
                    data: getAutoReply(), receiver: sender, desc: "离线");
            List<V2TimMessage> list = new List.empty(growable: true);
            list.add(res.data);
            Provider.of<CurrentMessageListModel>(context, listen: false)
                .addMessage("c2c_" + sender, list);
          } else {}

          //EasyLoading.dismiss();

        } else {
          V2TimValueCallback<V2TimMessage> res = await TencentImSDKPlugin
              .v2TIMManager.v2TIMMessageManager
              .sendCustomMessage(
                  data: "他/她可能离开了一会～", receiver: sender, desc: "离线");
          List<V2TimMessage> list = new List.empty(growable: true);
          list.add(res.data);
          Provider.of<CurrentMessageListModel>(context, listen: false)
              .addMessage("c2c_" + sender, list);
        }
      } else {
        print("sender=========:" + sender);
        print("userId:" + userId.data);
      }
    } else {}
  }

  _listingIm() {
    V2TIMManager timManager = TencentImSDKPlugin.v2TIMManager;
    //会话监听
    timManager.getConversationManager().setConversationListener(
          listener: new V2TimConversationListener(
            onConversationChanged: (conversationList) {
              try {
                //如果当前会话在使用中，也更新一下
                print(conversationList[0].lastMessage.sender.toString() +
                    "sadasdsa!!!!");
                if (conversationList[0].lastMessage.elemType == 2 &&
                    conversationList[0].lastMessage.customElem.desc == "离线") {
                } else {
                  print(conversationList[0].lastMessage.sender.toString() +
                      "sadasdsa!!!!");
                  sendLeaveData(conversationList[0].lastMessage.sender);
                }
                setState(() {
                  _onRefresh();
                });
              } catch (e) {}
            },
            onNewConversation: (conversationList) {
              try {
                // showToast("来新会话了！");
                Provider.of<ConversionModel>(context, listen: false)
                    .setConversionList(conversationList);
                //如果当前会话在使用中，也更新一下
                setState(() {
                  _data = conversationList;
                });
              } catch (e) {}
            },
            onSyncServerFailed: () {},
            onSyncServerFinish: () {},
            onSyncServerStart: () {},
          ),
        );
  }

  getMessage() async {
    _data = (await TencentImSDKPlugin.v2TIMManager
            .getConversationManager()
            .getConversationList(count: 1000, nextSeq: "0"))
        as List<V2TimConversation>;
    //print("当前会话长度${data.data.conversationList.length}");

    List<V2TimConversation> newList =
        data.data.conversationList.cast<V2TimConversation>();
    Provider.of<ConversionModel>(
      context,
      listen: false,
    ).setConversionList(newList);
  }

  @override
  void dispose() {
    super.dispose();
    // TencentImPlugin.removeListener(_imListener);
  }

  // /// IM监听器
  // _imListener(type, params) {
  //   if (type == TencentImListenerTypeEnum.ConversationChanged) {
  //     _onRefresh();
  //   }
  // }

  /// 刷新事件
  Future<dynamic> _onRefresh() async {
    return await TencentImSDKPlugin.v2TIMManager
        .getConversationManager()
        .getConversationList(count: 1000, nextSeq: "0")
        .then((value) {
      List<V2TimConversation> newList =
          value.data.conversationList.cast<V2TimConversation>();

      setState(() {
        _data = newList;
      });
      _data.forEach((element) {
        print("数据222；：：：" + element.showName);
      });
    });

    print("当前会话长度${data.data.conversationList.length}");
  }

  /// 会话点击事件
  _onConversationClick(V2TimConversation data) async {
    Get.to(
        MessageC2cPage(data.showName, data.type, data.userID, data.faceUrl,
            data.conversationID),
        arguments: data);
  }

  _conversationWidget() {
    dev.log(packageName + "comming！");
    conversationList = [];
    conversationList.add(InkWell(
      onTap: () {
        flag = false;
        setState(() {});
        dev.log(packageName + "搜索聊天记录跳转");
        Get.to(() => SearchUserPage());
        // Get.to(() => AddFriendPage());
      },
      child: Container(
          height: ScreenUtil().setHeight(32),
          alignment: Alignment.center,
          padding: EdgeInsets.only(left: 20),
          margin: EdgeInsets.only(
              left: ScreenUtil().setWidth(10),
              top: ScreenUtil().setHeight(10),
              right: ScreenUtil().setWidth(15)),
          decoration: BoxDecoration(
              color: Color.fromRGBO(241, 241, 241, 1),
              borderRadius: BorderRadius.circular(6)),
          child: Text(
            "搜索联系人、聊天记录",
            style: TextStyle(
                fontSize: 15, color: Color.fromRGBO(153, 153, 153, 1)),
          )),
    ));
    conversationList.add(SizedBox());
    _data == null
        ? []
        : _data.map((e) {
            if (e.isPinned) {
              conversationList.add(Slidable(
                actionPane: SlidableScrollActionPane(), //滑出选项的面板 动画
                actionExtentRatio: 0.25,

                secondaryActions: <Widget>[
                  //右侧按钮列表
                  IconSlideAction(
                      caption: '取消置顶',
                      color: Colors.black45,
                      icon: Icons.more_horiz,
                      closeOnTap: true,
                      onTap: () {
                        TencentImSDKPlugin.v2TIMManager.v2ConversationManager
                            .pinConversation(
                                conversationID: e.conversationID,
                                isPinned: false)
                            .then((value) {
                          if (value.code == 0) {
                            showToast("取消顶置成功");

                            _onRefresh();
                          }
                        }); //_showSnackBar('More'),
                      }),
                  IconSlideAction(
                    caption: '删除',
                    color: Colors.red,
                    icon: Icons.delete,
                    closeOnTap: true,
                    onTap: () {
                      //_showSnackBar('Delete');
                      flag = false;
                      setState(() {});
                      TencentImSDKPlugin.v2TIMManager.v2ConversationManager
                          .deleteConversation(conversationID: e.conversationID)
                          .then((value) {
                        {
                          if (value.code == 0) {
                            showToast("删除成功");
                            Provider.of<CurrentMessageListModel>(context,
                                    listen: false)
                                .deleteMessage(e.conversationID);
                          }
                          _onRefresh();
                        }
                      });
                    },
                  ),
                ],

                child: Container(
                  color: ZdColor.rgba(249, 249, 249, 1),
                  child: ListTile(
                    onTap: () {
                      flag = false;
                      setState(() {});
                      _onConversationClick(e);
                    },
                    leading: Container(
                      width: 48.w,
                      height: 55.w,
                      child: Stack(
                        children: [
                          Positioned(
                            top: 3.w,
                            child: Container(
                                height: 40.w,
                                width: 40.w,
                                decoration: BoxDecoration(
                                    borderRadius: BorderRadius.circular(6),
                                    color: Colors.greenAccent,
                                    image: e.faceUrl == null || e.faceUrl == ""
                                        ? null
                                        : DecorationImage(
                                            image: CachedNetworkImageProvider(
                                            e.faceUrl,
                                          ))),
                                child: ClipRRect(
                                  borderRadius: BorderRadius.circular(6),
                                  child: CachedNetworkImage(
                                    imageUrl: e.faceUrl ?? HEADER_URL,
                                    fit: BoxFit.cover,
                                  ),
                                )),
                          ),
                          Positioned(
                              left: 32.w,
                              child: Container(
                                child: e.unreadCount > 0
                                    ? PhysicalModel(
                                        color: Colors.transparent,
                                        borderRadius: BorderRadius.circular(9),
                                        clipBehavior: Clip.antiAlias,
                                        child: Container(
                                          color: HiColor.red,
                                          width: 16.w,
                                          height: 16.w,
                                          child: Column(
                                            mainAxisAlignment:
                                                MainAxisAlignment.center,
                                            crossAxisAlignment:
                                                CrossAxisAlignment.center,
                                            children: [
                                              Text(
                                                e.unreadCount > 99
                                                    ? '...'
                                                    : e.unreadCount.toString(),
                                                textAlign: TextAlign.center,
                                                textWidthBasis:
                                                    TextWidthBasis.parent,
                                                style: TextStyle(
                                                  color: Colors.white,
                                                  fontSize: sp(10),
                                                ),
                                              )
                                            ],
                                          ),
                                        ),
                                      )
                                    : null,
                                width: 16.w,
                                height: 16.w,
                                margin: EdgeInsets.only(right: 16),
                              ))
                        ],
                      ),
                    ),
                    title: Text(
                      e.showName ?? "",
                      style: TextStyle(
                        fontSize: sp(15),
                      ),
                    ),
                    subtitle: Row(
                      children: [
                        Container(
                          child: Text(
                            e.draftText == null ? "" : "[草稿]",
                            style: TextStyle(
                                fontSize: sp(12),
                                color: ZdColor.rgba(153, 153, 153, 1)),
                          ),
                        ),
                        Container(
                          width: 200,
                          child: Text(
                            e.draftText == null
                                ? e.lastMessage != null
                                    ? e.lastMessage.status == 6
                                        ? "'${e.lastMessage.isSelf ? "你" : '对方'}'撤回了一条消息"
                                        : e.lastMessage.elemType ==
                                                    MessageElemType
                                                        .V2TIM_ELEM_TYPE_TEXT &&
                                                e.lastMessage.status != 6
                                            ? e.lastMessage.textElem.text
                                            : e.lastMessage.elemType ==
                                                        MessageElemType
                                                            .V2TIM_ELEM_TYPE_GROUP_TIPS &&
                                                    e.lastMessage.status != 6
                                                ? '【系统消息】'
                                                : e.lastMessage.elemType ==
                                                            MessageElemType
                                                                .V2TIM_ELEM_TYPE_SOUND &&
                                                        e.lastMessage.status !=
                                                            6
                                                    ? '【语音消息】'
                                                    : e.lastMessage.elemType ==
                                                                MessageElemType
                                                                    .V2TIM_ELEM_TYPE_CUSTOM &&
                                                            e.lastMessage.status !=
                                                                6
                                                        ? '【新消息】'
                                                        : e.lastMessage.elemType ==
                                                                    MessageElemType
                                                                        .V2TIM_ELEM_TYPE_IMAGE &&
                                                                e.lastMessage
                                                                        .status !=
                                                                    6
                                                            ? '【图片】'
                                                            : e.lastMessage.elemType == MessageElemType.V2TIM_ELEM_TYPE_VIDEO && e.lastMessage.status != 6
                                                                ? '【视频】'
                                                                : e.lastMessage.elemType == MessageElemType.V2TIM_ELEM_TYPE_FILE && e.lastMessage.status != 6
                                                                    ? '【文件】'
                                                                    : e.lastMessage.elemType == MessageElemType.V2TIM_ELEM_TYPE_FACE && e.lastMessage.status != 6
                                                                        ? '【表情】'
                                                                        : '4'
                                    : "1"
                                : "2",
                            style: TextStyle(
                                fontSize: sp(12),
                                color: ZdColor.rgba(153, 153, 153, 1)),
                            overflow: TextOverflow.ellipsis,
                            softWrap: false,
                          ),
                        ),
                      ],
                    ),
                    trailing: Column(
                      children: [
                        Container(
                          padding: EdgeInsets.only(top: 10),
                          child: Text(
                            //TODO 需优化格式化时间
                            getDate(e.lastMessage != null
                                    ? e.lastMessage.timestamp
                                    : 0) ??
                                "",
                            style: TextStyle(
                                fontSize: sp(12),
                                color: ZdColor.rgba(153, 153, 153, 1)),
                          ),
                        )
                      ],
                    ),
                  ),
                ),
              ));
            }
            if (!e.isPinned) {
              conversationList.add(
                Slidable(
                  actionPane: SlidableScrollActionPane(), //滑出选项的面板 动画
                  actionExtentRatio: 0.25,
                  closeOnScroll: true,
                  secondaryActions: <Widget>[
                    //右侧按钮列表
                    IconSlideAction(
                      caption: '顶置',
                      color: Colors.black45,
                      icon: Icons.more_horiz,
                      closeOnTap: true,
                      onTap: () {
                        flag = false;
                        setState(() {});
                        TencentImSDKPlugin.v2TIMManager.v2ConversationManager
                            .pinConversation(
                                conversationID: e.conversationID,
                                isPinned: true)
                            .then((value) {
                          if (value.code == 0) {
                            showToast("顶置成功");
                            setState(() {
                              _onRefresh();
                            });
                          }
                        });
                      }, //_showSnackBar('More'),
                    ),
                    IconSlideAction(
                      caption: '删除',
                      color: Colors.red,
                      icon: Icons.delete,
                      closeOnTap: true,
                      onTap: () {
                        flag = false;
                        setState(() {});
                        TencentImSDKPlugin.v2TIMManager.v2ConversationManager
                            .deleteConversation(
                                conversationID: e.conversationID)
                            .then((value) {
                          {
                            if (value.code == 0) {
                              TencentImSDKPlugin
                                  .v2TIMManager.v2ConversationManager
                                  .getConversationList(
                                      nextSeq: "0", count: 1000)
                                  .then((value) {
                                if (value.code == 0) {
                                  Provider.of<ConversionModel>(context,
                                          listen: false)
                                      .removeConversionByConversationId(
                                          e.conversationID);
                                  Provider.of<CurrentMessageListModel>(context,
                                          listen: false)
                                      .deleteMessage(e.conversationID);
                                  setState(() {
                                    _data = value.data.conversationList;
                                  });
                                }
                              });
                            }
                          }
                        });
                        //_
                      },
                    ),
                  ],

                  child: ListTile(
                    onTap: () {
                      flag = false;
                      setState(() {});
                      _onConversationClick(e);
                    },
                    leading: Container(
                      width: 48.w,
                      height: 45.w,
                      child: Stack(
                        children: [
                          Positioned(
                            top: 3.w,
                            child: Container(
                                height: 40.w,
                                width: 40.w,
                                decoration: BoxDecoration(
                                    borderRadius: BorderRadius.circular(6),
                                    color: Colors.greenAccent,
                                    image: e.faceUrl == null || e.faceUrl == ""
                                        ? null
                                        : DecorationImage(
                                            image: CachedNetworkImageProvider(
                                            e.faceUrl,
                                          ))),
                                child: ClipRRect(
                                  borderRadius: BorderRadius.circular(6),
                                  child: CachedNetworkImage(
                                    imageUrl: e.faceUrl ?? HEADER_URL,
                                    fit: BoxFit.cover,
                                  ),
                                )),
                          ),
                          Positioned(
                              left: 32.w,
                              child: Container(
                                child: e.unreadCount > 0
                                    ? PhysicalModel(
                                        color: Colors.transparent,
                                        borderRadius: BorderRadius.circular(9),
                                        clipBehavior: Clip.antiAlias,
                                        child: Container(
                                          color: HiColor.red,
                                          width: 16.w,
                                          height: 16.w,
                                          child: Column(
                                            mainAxisAlignment:
                                                MainAxisAlignment.center,
                                            crossAxisAlignment:
                                                CrossAxisAlignment.center,
                                            children: [
                                              Text(
                                                e.unreadCount > 99
                                                    ? '...'
                                                    : e.unreadCount.toString(),
                                                textAlign: TextAlign.center,
                                                style: TextStyle(
                                                  color: Colors.white,
                                                  fontSize: sp(10),
                                                ),
                                              )
                                            ],
                                          ),
                                        ),
                                      )
                                    : null,
                                width: 16.w,
                                height: 16.w,
                              ))
                        ],
                      ),
                    ),
                    title: Text(
                      e.showName ?? "",
                      style: TextStyle(
                        fontSize: sp(15),
                      ),
                    ),
                    subtitle: Row(
                      children: [
                        Container(
                          child: Text(
                            e.draftText == null ? "" : "[草稿]",
                            style: TextStyle(
                                fontSize: sp(12),
                                color: ZdColor.rgba(153, 153, 153, 1)),
                          ),
                        ),
                        Container(
                          width: 200,
                          child: Text(
                            e.draftText == null
                                ? e.lastMessage != null
                                    ? e.lastMessage.status == 6
                                        ? "${e.lastMessage.isSelf ? "你" : '对方'}撤回了一条消息"
                                        : e.lastMessage.elemType ==
                                                    MessageElemType
                                                        .V2TIM_ELEM_TYPE_TEXT &&
                                                e.lastMessage.status != 6
                                            ? e.lastMessage.textElem.text
                                            : e.lastMessage.elemType ==
                                                    MessageElemType
                                                        .V2TIM_ELEM_TYPE_GROUP_TIPS
                                                ? '【系统消息】'
                                                : e.lastMessage.elemType ==
                                                            MessageElemType
                                                                .V2TIM_ELEM_TYPE_SOUND &&
                                                        e.lastMessage.status !=
                                                            6
                                                    ? '【语音消息】'
                                                    : e.lastMessage.elemType ==
                                                                MessageElemType
                                                                    .V2TIM_ELEM_TYPE_CUSTOM &&
                                                            e.lastMessage.status !=
                                                                6
                                                        ? '【新消息】'
                                                        : e.lastMessage.elemType ==
                                                                    MessageElemType
                                                                        .V2TIM_ELEM_TYPE_IMAGE &&
                                                                e.lastMessage.status !=
                                                                    6
                                                            ? '【图片】'
                                                            : e.lastMessage.elemType ==
                                                                        MessageElemType.V2TIM_ELEM_TYPE_VIDEO &&
                                                                    e.lastMessage.status != 6
                                                                ? '【视频】'
                                                                : e.lastMessage.elemType == MessageElemType.V2TIM_ELEM_TYPE_FILE && e.lastMessage.status != 6
                                                                    ? '【文件】'
                                                                    : e.lastMessage.elemType == MessageElemType.V2TIM_ELEM_TYPE_FACE && e.lastMessage.status != 6
                                                                        ? '【表情】'
                                                                        : ''
                                    : ""
                                : "",
                            style: TextStyle(
                                fontSize: sp(12),
                                color: ZdColor.rgba(153, 153, 153, 1)),
                            overflow: TextOverflow.ellipsis,
                            softWrap: false,
                          ),
                        ),
                      ],
                    ),
                    trailing: Column(
                      children: [
                        Container(
                          padding: EdgeInsets.only(top: 10),
                          child: Text(
                            //TODO 需优化格式化时间
                            getDate(e.lastMessage != null
                                    ? e.lastMessage.timestamp
                                    : 0) ??
                                "",
                            style: TextStyle(
                                fontSize: sp(12),
                                color: ZdColor.rgba(153, 153, 153, 1)),
                          ),
                        )
                      ],
                    ),
                  ),
                ),
              );
            }

            conversationList.add(Divider(
              height: 1,
              indent: width(65),
              endIndent: width(15),
            ));
          }).toList();
  }

  @override
  Widget build(BuildContext context) {
    _conversationWidget();

    return Scaffold(
      appBar: AppBar(
        elevation: 0,
        centerTitle: false,
        title: Container(
          width: ScreenUtil().setWidth(100),
          height: 30,
          child: Text(
            "消息",
            style: TextStyle(
                fontSize: ScreenUtil().setSp(22), color: Colors.black),
          ),
        ),
        actions: [
          // topRightClean(),
          InkWell(
            onTap: () {
              dev.log(packageName + "添加好友");
              setState(() {
                flag = !flag;
              });
            },
            child: Container(
                width: ScreenUtil().setWidth(40),
                alignment: Alignment.center,
                margin: EdgeInsets.only(right: ScreenUtil().setWidth(10)),
                child: Image.asset(
                  "images/增加.png",
                  height: 18.w,
                  width: ScreenUtil().setWidth(18),
                  fit: BoxFit.contain,
                )),
          ),
        ],
      ),
      body: GestureDetector(
        onTap: () {
          flag = false;
          setState(() {});
        },
        child: Stack(
          children: [
            Container(
              color: Colors.white,
              child: RefreshIndicator(
                  key: _refreshIndicatorKey,
                  onRefresh: _onRefresh,
                  color: Colors.greenAccent,
                  //指示器颜色，默认ThemeData.accentColor
                  backgroundColor: Colors.white,
                  //指示器背景颜色，默认ThemeData.canvasColor
                  child: ListView(
                    children: conversationList,
                  )),
            ),
            flag
                ? Positioned(
                    top: 0,
                    right: 10.w,
                    child: Container(
                      alignment: Alignment.center,
                      height: 120,
                      width: 140.w,
                      decoration: BoxDecoration(
                          image: DecorationImage(
                              image: AssetImage("images/adduser.png"))),
                      child: Column(
                        children: [
                          InkWell(
                            onTap: () {
                              flag = false;
                              setState(() {});
                              Get.to(() => NewFriendsPage());
                            },
                            child: Row(
                              children: <Widget>[
                                Container(
                                  margin: EdgeInsets.only(
                                    left: ScreenUtil().setWidth(24),
                                    top: 30,
                                  ),
                                  child: SvgPicture.asset(
                                    "images/addicon.svg",
                                    height: 24,
                                    width: ScreenUtil().setWidth(23),
                                    color: Colors.white,
                                  ),
                                ),
                                Container(
                                  margin: EdgeInsets.only(
                                    left: ScreenUtil().setWidth(5),
                                    top: 30,
                                  ),
                                  child: Text(
                                    "添加朋友",
                                    style: TextStyle(
                                        fontSize: ScreenUtil().setSp(13),
                                        color: Colors.white),
                                  ),
                                ),
                              ],
                            ),
                          ),
                          Container(
                            margin: EdgeInsets.only(
                              left: ScreenUtil().setWidth(5),
                              top: 12,
                            ),
                            child: Divider(
                              height: 1,
                              indent: ScreenUtil().setWidth(12),
                              endIndent: ScreenUtil().setWidth(12),
                              color: Color.fromRGBO(64, 64, 64, 1),
                              thickness: ScreenUtil().setHeight(1),
                            ),
                          ),
                          //todo 扫一扫
                          InkWell(
                            onTap: () {
                              flag = false;
                              setState(() {});
                              _zXingCode();
                            },
                            child: Row(
                              children: <Widget>[
                                Container(
                                  margin: EdgeInsets.only(
                                    left: ScreenUtil().setWidth(24),
                                    top: 8,
                                  ),
                                  child: Image.asset(
                                    "images/ic_zxing_function.png",
                                    height: 24,
                                    width: ScreenUtil().setWidth(23),
                                  ),
                                ),
                                Container(
                                  margin: EdgeInsets.only(
                                    left: ScreenUtil().setWidth(8),
                                    top: 8,
                                  ),
                                  child: Text(
                                    "扫一扫",
                                    style: TextStyle(
                                        fontSize: ScreenUtil().setSp(13),
                                        color: Colors.white),
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),
                  )
                : Container()
          ],
        ),
      ),
    );
  }

  InkWell topRightClean() {
    return InkWell(
      onTap: () {
        dev.log(packageName + "清除");
        flag = false;
        setState(() {});
        // Get.to(MessageTest());
      },
      child: Container(
          width: ScreenUtil().setWidth(40),
          alignment: Alignment.center,
          margin: EdgeInsets.only(right: ScreenUtil().setWidth(10)),
          child: Image.asset(
            "images/清除.png",
            height: 18.w,
            width: ScreenUtil().setWidth(18),
            fit: BoxFit.contain,
          )),
    );
  }

  getDate(int min) {
    if (min == 0) {
      return "";
    }
    if (DateUtil.isToday(min * 1000)) {
      print(DateUtil.formatDate(DateTime.fromMillisecondsSinceEpoch(min * 1000),
              format: DateFormats.h_m)
          .toString());
      return DateUtil.formatDate(
              DateTime.fromMillisecondsSinceEpoch(min * 1000),
              format: DateFormats.h_m)
          .toString();
    } else if (DateUtil.isYesterday(
        DateTime.fromMillisecondsSinceEpoch(min * 1000), DateTime.now())) {
      return "昨天";
    } else if (DateUtil.isWeek(min * 1000) &&
        !DateUtil.isYesterday(
            DateTime.fromMillisecondsSinceEpoch(min * 1000), DateTime.now()) &&
        !DateUtil.isToday(min * 1000)) {
      return DateUtil.getWeekday(
          DateTime.fromMillisecondsSinceEpoch(min * 1000),
          languageCode: "zh");
    } else if (!DateUtil.isWeek(min * 1000) &&
        !DateUtil.isYesterday(
            DateTime.fromMillisecondsSinceEpoch(min * 1000), DateTime.now()) &&
        !DateUtil.isToday(min * 1000)) {
      return DateUtil.formatDate(
          DateTime.fromMillisecondsSinceEpoch(min * 1000),
          format: DateFormats.zh_mo_d);
    }
  }

  void deleteMessageFromLocalStorage(String msgId, conID) async {
    V2TimCallback res = await TencentImSDKPlugin.v2TIMManager
        .getMessageManager()
        .deleteMessageFromLocalStorage(msgID: msgId);
    if (res.code == 0) {
      showToast("删除成功");
      Navigator.pop(context, '清空聊天记录');
      Provider.of<CurrentMessageListModel>(context, listen: false)
          .deleteMessage(conID);
    }
    print(res.toJson());
  }

  ///--------------------------------扫描二维码 start

  _zXingCode() async {
    print('---扫描----message_page');

    var value = await Get.to(QRViewExample());
    if (value == null) return;
    if (value.contains("user")) {
      String key = "qrCodeKey=";
      int index = value.indexOf(key);
      String _userMsg = value.substring(index + key.length, value.length);
      // print('---扫描结果----$_userMsg');
      EasyLoading.show(status: "查询中...");
      getServiceData(_userMsg);
    } else if (value.contains("webLogin")) {
      EasyLoading.show();
      _qrLogin(value);
    } else {
      toast("扫描结果:$value");
    }
  }

  SelectUser user;

  getServiceData(userId) async {
    user = await SelectUserDao.getUserInfo(userId);
    if (user.data.length == 0) {
      toast("暂未查找到该好友");
      EasyLoading.dismiss();
    } else {
      _findUserFriends();
    }
  }

  _findUserFriends() async {
    print('二维码  _findUserFriends');
    try {
      V2TimValueCallback<List<V2TimFriendInfoResult>> v2TimFriendInfoResult =
          await TencentImSDKPlugin.v2TIMManager.v2TIMFriendshipManager
              .getFriendsInfo(userIDList: [user.data[0].userId.toString()]);
      EasyLoading.dismiss();

      if (v2TimFriendInfoResult.data.length == 0) {
        toast("暂未查找到该好友");
      } else {
        print("二维码 跳转页面：UserCheckPage");

        Get.to(() => UserCheckPage(
              userId: user.data[0].userId.toString(),
              ziyuId: user.data[0].account.toString(),
              userEntity: v2TimFriendInfoResult.data[0].friendInfo.userProfile,
          type: 2,
            ));
      }
    } catch (e) {
      EasyLoading.dismiss();
      toast("暂未查找到该好友");
      print(e);
    }
  }

  void _qrLogin(value) async {
    String key = "qrCodeKey=";
    int index = value.indexOf(key);
    String _userMsg = value.substring(index + key.length, value.length);
    BaseModel _model = await LoginInitDao.qrLogin(_userMsg, 1);
    if (_model.resultCode == 1) {
      Future.delayed(Duration(milliseconds: 500), () {
        EasyLoading.dismiss();
        Get.to(LoginZxingDialog(_userMsg));
      });
    } else {
      EasyLoading.dismiss();
      toast("登录失败：${_model.resultMsg}");
    }
  }

  ///--------------------------------扫描二维码 end

}
